package com.atguigu.gulimall.common.utils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
 * @author Luo Sheng
 * @school YiBin university
 * @create 2023-03-07 15:32
 */



/**
 * 枚举校验注解处理类
 * 校验策略
 */
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {

    private Set<String> strValues;
    private Set<Integer> intValues;

    @Override
    public void initialize(EnumValue constraintAnnotation) {
        intValues = new HashSet<>();
        strValues = new HashSet<>();
        if (constraintAnnotation.intValues().length > 0) {
            for (int value : constraintAnnotation.intValues()) {
                intValues.add(value);
            }
        }
        if (constraintAnnotation.strValues().length > 0) {
            strValues.addAll(Arrays.asList(constraintAnnotation.strValues()));
        }
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value instanceof String) {
            return strValues.contains((String) value);
        } else if (value instanceof Integer) {
            return intValues.contains((Integer) value);
        }
        return false;
    }
}